import {doAuth} from '../api/api'
import { STORAGE_KEY } from '../api/config'
import {LENGYU_SUCCESS_CODE}  from '../utils/request'

export const formatTime = (date: Date) => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return (
    [year, month, day].map(formatNumber).join('/') +
    ' ' +
    [hour, minute, second].map(formatNumber).join(':')
  )
}

const formatNumber = (n: number) => {
  const s = n.toString()
  return s[1] ? s : '0' + s
}
export async function doLogin(){
  wx.showLoading({
    title: '登录中',
  })
  let lastDate = wx.getStorageSync("doLoginTime")
  if(lastDate && new Date().getTime() - lastDate.getTime() < 1000*60 *60 *2){
    console.log("两小时内只登录一次")
    wx.hideLoading()
    return
  }

  let resCode = await doWxLogin()
  if(resCode != "error"){
     await doLengyuLogin(resCode);
  }
  wx.hideLoading()
}

function doWxLogin():Promise<string>{
    // 登录
    return new Promise((resolve, reject)=> {
      wx.login({
        timeout:30000,//设置超时时间ms
        success: res => {
          console.log(res.code)
          // 发送 res.code 到后台换取 openId, sessionKey, unionId
          resolve(res.code)
        },
        fail: res => {
          console.log("登录失败")
          console.log(res)
          reject("error");
        },
        
      })
    })
  }
async function doLengyuLogin(code:string){
  let resData = await doAuth(code);
  console.log(resData);
  if(resData.code==LENGYU_SUCCESS_CODE){
    if(resData.data.openid){
      wx.setStorageSync('openId', resData.data.openid)
    }
    if(resData.data.session_key){
      wx.setStorageSync('sessionKey', resData.data.session_key)
    }
    if(resData.data.roles){
      wx.setStorageSync('roles', resData.data.roles)
    }
    if(resData.data.lengyu_token){
      wx.setStorageSync('token', resData.data.lengyu_token)
      wx.setStorageSync('doLoginTime',new Date())
    }
    if(resData.data.nickName){
      wx.setStorageSync(STORAGE_KEY.NICK_NAME, resData.data.nickName)
    }
    if(resData.data.avatar){
      wx.setStorageSync(STORAGE_KEY.AVATAR, resData.data.avatar)
    }
    if(resData.data.userId){
      wx.setStorageSync('userId', resData.data.userId)
    }
  }
}
